<?php

namespace app\admin\model;

use app\admin\validate\IndexValidate;
use app\admin\validate\LoginValidate;
use think\Model;
use think\model\concern\SoftDelete;

class Admin extends Model
{
    public function postLogin(array $data){
        $validate =new LoginValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        return Admin::create($data);
    }
    //更新
    public function putLogin(array $data){
        $validate =new LoginValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        $info =Admin::where('username',$data['username'])->find();
        if(!empty($data['newpassword'])) {
            if ($data['newpassword'] == $data['password']) {
                if ($data['password'] == $info['password']) {
                    return 3;
                } else {
                    Admin::where('username', $data['username'])->update(['password' => $data['password']]);
                    return 1;
                }
            } else {
                return 2;
            }
        }else{
            return 4;
        }
    }
    //查
    public function getLogin(array $data){
        $validate =new LoginValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        $info =Admin::where('username',$data['username'])->find();
        if($info){
            if($info['password']==$data['password']){
                return 1;
            }else{
                return '密码错误';
            }
        }
        return '用户名错误';
    }
    //删除
    public function deleteLogin($id){
        return Admin::destory($id);
    }

    public function insert(){
        return Admin::select();
    }
    //个人中心修改
    public function personal($data){
        $validate =new IndexValidate();
        if(!$validate->check($data)){
            return $validate->getError();
        }
        if(!empty($data['mylogo'])){
            $dir ="./uploads/logo/".date('Ymd');
            if(!file_exists($dir)){
                mkdir($dir,0777,true);
            }
            //更改图片路径
            $truepath =str_replace('mylogo','logo',$data['mylogo']);
            //移动图片
            rename($data['mylogo'],$truepath);
            $data['mylogo'] =$truepath;
        }
        if(Admin::update($data)){
            return 1;
        }else{
            return 2;
        };
    }
}
